/*
 *  shared_region.cc
 *  Untitled
 *
 *  Created by Ben Nolan on 3/11/08.
 *  Copyright 2008 __MyCompanyName__. All rights reserved.
 *
 */

#include "server_region.h"
#include "listener.h"
#include "message.h"
#include <iostream>

#include <boost/foreach.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

namespace Wonderland{

ServerRegion::ServerRegion(boost::asio::io_service* io) : timer_(*io, boost::posix_time::seconds(0.1)){
	timer_.async_wait(boost::bind(&Wonderland::ServerRegion::sendUpdates, this));
}

void ServerRegion::addListener(Wonderland::Listener* l){
	listeners_.insert(l);
	
	std::cout << "Sending " << l->getVisibleNodes().size() << " nodes to listener in initial dump\n";
	
	BOOST_FOREACH(Node *node, l->getVisibleNodes()){
		Wonderland::Message *message = new Wonderland::Message(node->toString());
		l->sendMessage(message);
	}
}

void ServerRegion::sendUpdates(){
	
	
	BOOST_FOREACH(NodeMapPair pair, dirtyNodes_){
		Wonderland::Message* message = new Wonderland::Message(pair.second->toString());
		
		BOOST_FOREACH(Wonderland::Listener* listener, listeners_){
			if(listener->interestedIn(*pair.second)){
				listener->sendMessage(message);
			}
		}

		// TODO: Use reference counting to delete the message
	}
	
	// Clear dirty nodes - upates are sent
	dirtyNodes_.clear();
	
	timer_.expires_from_now(boost::posix_time::millisec(10));
	timer_.async_wait(boost::bind(&Wonderland::ServerRegion::sendUpdates, this));
}

}